---
--类名: MakeView.lua
--创建日期: 2017-12-22
--创建人: 陈小虎
--功能描述:
--修改内容:
--修改日期:
--修改人:
--修改备注:
--

local MoLayer = require("app.widget.MoLayer")
local IconRender = require("app.widget.renders.IconRender")
local AttrRender = require("app.widget.renders.AttrRender")
local Equip = require("app.public.dao.Equip")
local MakeItem = import("..views.MakeItem")


local dataPanelOriginHeight = 0 -- 装备属性panel原始高
local dataAttrPanelHeight = 0 -- 装备属性单挑文本高
local dataLineOriginPos = 0 -- 装备属性初始位置
local dataAttrOriginPos_1 = 0 -- 装备属性1初始位置
local dataAttrOriginPos_2 = 0 -- 装备属性2初始位置
local dataAttrOriginPos_3 = 0 -- 装备属性3初始位置

local string_split = string.split
local string_find = string.find

local MakeView = class("MakeView",function()
    return display.newLayer()
end)

function MakeView:ctor(model)
	self._model = model

	self:setNodeEventEnabled(true)

    self.mUINode = cc.uiloader:load(Res.ManufacturingUI)
    self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width,display.height))
    ccui.Helper:doLayout(self.mUINode)

    self:init()

    self:updatePowerValue()
end

-- 接口名不可更改，保持与viewBase一致
function MakeView:getViewType()
	return app.mvc.VIEWTYPE_BLUR
end

function MakeView:init()
	self._makeInfoItems = {}

	local rootPanel = self.mUINode:getChildByName("Panel")
	self._toolsNode = rootPanel:getChildByName("tools")
	self._makeNode = rootPanel:getChildByName("make")
	local makeRootPanel = self._makeNode:getChildByName("Panel_1")
	local makePowerRoot = makeRootPanel:getChildByName("Panel_power")
	self._powerNumText = makePowerRoot:getChildByName("num")
	self._mainPage = makeRootPanel:getChildByName("node_up")
	self._maxLevelPage = makeRootPanel:getChildByName("node_max")
	self._makePage = makeRootPanel:getChildByName("node_make")

	local rootAttrNode = self._makePage:findChild("Panel/Panel_tips")
	local rootAttrPanel = rootAttrNode:getChildByName("Panel")
	dataPanelOriginHeight = rootAttrPanel:getChildByName("Panel_data"):getContentSize().height
	dataLineOriginPos = rootAttrPanel:findChild("Panel_data/line"):getPositionY()
	dataAttrOriginPos_1 = rootAttrPanel:findChild("Panel_data/data_1"):getPositionY()
	dataAttrPanelHeight = rootAttrPanel:findChild("Panel_data/data_1/Panel"):getContentSize().height
	dataAttrOriginPos_2 = rootAttrPanel:findChild("Panel_data/data_2"):getPositionY()
	dataAttrOriginPos_3 = rootAttrPanel:findChild("Panel_data/data_3"):getPositionY()

	self._makeList = makeRootPanel:getChildByName("ListView")

	local toolRootPanel = self._toolsNode:getChildByName("Panel")
	local toolPowerRoot = toolRootPanel:getChildByName("Panel_power")
	self._powerNumText1 = toolPowerRoot:getChildByName("num")
	self._toolsMenuList = toolRootPanel:getChildByName("ListView")
	self._tollsList = toolRootPanel:getChildByName("ListView_tools")

	makePowerRoot:setTouchEnabled(true)
    makePowerRoot:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.began then
        	app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = {itemId = 96,tipsType = Enums.TipsType.daibi}})
        end
    end)
    toolPowerRoot:setTouchEnabled(true)
    toolPowerRoot:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.began then
        	app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = {itemId = 96,tipsType = Enums.TipsType.daibi}})
        end
    end)
	local btnClose = rootPanel:getChildByName("Button_close")
	btnClose:addClickEventListener(function(sender)
		self:closeCallback()
	end)

	self._btnMake = rootPanel:findChild("Panel_tab/selected_btn_1")
	self._btnTools = rootPanel:findChild("Panel_tab/selected_btn_2")
	self._btnMake:addClickEventListener(function(sender)
		self:switchOption(true)
	end)
	self._btnTools:setVisible(false)
	self._btnTools:addClickEventListener(function(sender)
		self:switchOption(false)
		self:fillToolsMenuList()
	end)
	self:switchOption(true)

	-- guide
	self._makeList:performWithDelay(function()
			self:checkGuide()
		end, 0)
end


-- 检查是否触发了引导
function MakeView:checkGuide()
    local funcId = Constant.FUNC_TYPE_COMPOUND
    local params = {
        scene = funcId,
        sceneSelf = self,
        getFunc = self.getGuideNodeFunc,
        nextFunc = self.checkGuide
    }
    EM:notify("checkGuide", params)
end

-- 获取引导node
function MakeView:getGuideNodeFunc(id)
    if id == 136 then
    	-- 生活技能说明提示
        return self._makeList:getItem(0):getChildByName("Panel")
    elseif id == 137 then
    	-- 体力提示
		return self._makeNode:findChild("Panel_1/Panel_power")
    end
end

function MakeView:onExit()
	executeFunc(self._clearCallback)
end

function MakeView:setClearCallback(callback)
	self._clearCallback = callback
end
function MakeView:setCloseCallback(callback)
	self._closeCallback = callback
end

function MakeView:closeCallback()
	if self._closeCallback then
		self._closeCallback()
	end
end

function MakeView:updatePowerValue(value)
	local powerValue = value or UD:getPower()
	if self._powerNumText then
		self._powerNumText:setString(powerValue)
	end
	if self._powerNumText1 then
		self._powerNumText1:setString(powerValue)
	end
end

function MakeView:switchMakePage(isMake)
	self._mainPage:setVisible(not isMake)
	self._maxLevelPage:setVisible(not isMake)
	self._makePage:setVisible(isMake)
end

function MakeView:updateMainPage(data,typeName)
	--typeName的意义何在？ 后面根本没用到
	local progress = data.exp / data.maxExp * 100
	local typeNameStr = string.format(L("manufactureLevel"),data.name)
	local expStr = data.exp .. "/" .. data.maxExp
	local levelStr = L("text_10000098") .. data.level

	if data.level >= data.maxLevel then
		self._mainPage:setVisible(false)
		self._maxLevelPage:setVisible(true)

		local root = self._maxLevelPage:getChildByName("Panel")
		local tipsTypeNameText = root:getChildByName("tlt")
		local levelText = root:getChildByName("lv")
		local expBarRoot = root:getChildByName("Panel_bar")
		local tipMax = root:getChildByName("tips")
		expBarRoot:setVisible( false )
		local expBar = expBarRoot:getChildByName("LoadingBar")
		local expText = expBarRoot:getChildByName("num")
		local iconNode = root:getChildByName("icon")
		if data.iconPath then
			iconNode:loadTexture(data.iconPath)
		end
		if typeNameStr then
			tipsTypeNameText:setString(typeNameStr)
		end
		levelText:setString(levelStr)
		if tipMax then
			local maxString = string.format(L("manufactureLevelMax"),data.name)
			tipMax:setString(maxString)
		end
		expBar:setPercent(progress)
		expText:setString(expStr)
	else
		self._mainPage:setVisible(true)
		self._maxLevelPage:setVisible(false)

		local root = self._mainPage:getChildByName("Panel")
		local Panel_make = root:getChildByName("Panel_make")
		local Panel_need = root:getChildByName("Panel_need")

		local iconNode = Panel_make:getChildByName("icon")
		if data.iconPath then
			iconNode:loadTexture(data.iconPath)
		end

		local levelText = Panel_make:getChildByName("lv")
		local tipsTypeNameText = Panel_make:getChildByName("tlt")
		local Panel_icon = Panel_make:getChildByName("Panel_icon")
		local expBarRoot = Panel_make:getChildByName("Panel_bar")
		local expBar = expBarRoot:getChildByName("LoadingBar")
		local expText = expBarRoot:getChildByName("num")

		local PanelGold = Panel_need:getChildByName("Panel_gold")

		local needLvDesc = PanelGold:getChildByName("lv_tlt")
		local needLvText = PanelGold:getChildByName("lv_num")
		local needCoinIcon = PanelGold:getChildByName("gold_icon")
		local needCoinText = PanelGold:getChildByName("gold_num")
		if not self._coinColor  then
			self._coinColor = needCoinText:getColor()
		end
		local btnLevelUp = Panel_need:getChildByName("Button_up")
		local itemRoot = Panel_need:getChildByName("Panel_item")

		levelText:setString(levelStr)

		expBar:setPercent(progress)
		expText:setString(expStr)

		if typeNameStr then
			tipsTypeNameText:setString(typeNameStr)
		end

		needLvDesc:setString(L("lua_code_text_311"))
		needLvText:setString(data.minLv)
		if UD:getPlayer().level < data.minLv then
			needLvText:setColor(cc.c3b(255,0,0))
		else
			needLvText:setColor(self._coinColor)
		end
		-- 设置居中
		display.setNodesMiddle(PanelGold, nil, needLvDesc, needLvText)

		self.isItemEnough = true
		local isCoinEnough = true

		btnLevelUp:addClickEventListener(function(sender)
			if not self.isItemEnough then
				display.pushToast(L("tips_1000075"))
				return
			end
			if UD:getPlayer().level < data.minLv then
				display.pushToast(L("tips_2000118"))
				return
			end
			if not isCoinEnough then
				display.pushToast(L("tips_2000046"))
				return
			end
			self._model:C2S_UpgradeLifeSkill()
		end)

		for i = 1,3 do
			local name = "icon_" .. i
			local iconNode = Panel_icon:getChildByName(name)
			if iconNode then
				iconNode:setVisible(false)
			end
		end

		local ulen = #data.unlockFormulas
		if ulen > 0 then
			local uWidth = Panel_icon:getContentSize().width
			for i,item in ipairs(data.unlockFormulas) do
				local name = "icon_" .. i
				local iconNode = Panel_icon:getChildByName(name)
				if iconNode then
					iconNode:setVisible(true)
			        local uiItem = IconRender.create(iconNode)
			        uiItem:setData(item)
			        uiItem:setTipEnable(true)
			        uiItem:setNumBgVisible(false)
			        local sWidth = iconNode:getContentSize().width + 10
			        local sx = (uWidth - ulen * sWidth) / 2 + (i - 1) * sWidth + 5
			        uiItem:setPosition(cc.p(sx,0))
				end
			end
		end


		for i = 1, 6 do
			local name = "icon_" .. i
			local itemNode = itemRoot:getChildByName(name)
			if itemNode then
				itemNode:setVisible(false)
			end
		end

		local daibiItem = nil
		local costArray
		if data.cost then
			costArray = string_split(data.cost,";")
		end
		if costArray then
			local items = {}
			for i,v in ipairs(costArray) do
				local item = UD:parseRewardToBagItem(v)
				if item and item.itemBagType == Enums.ItemBagType.daibi then
					daibiItem = item
				else
					table.insert(items,item)
				end
			end

			local len = #items
			for i,item in ipairs(items) do
				local name = "icon_" .. i
				local itemNode = itemRoot:getChildByName(name)
				if itemNode then
					itemNode:setVisible(true)
		            local uiItem = IconRender.create(itemNode)
		            uiItem:setData(item)
		            uiItem:setTipEnable(true)
		            uiItem:setNumBgVisible(true)
		            -- itemRoot:addChild(uiItem)
		            local hasNum = UD:getNumByRenderData( item )
	                local isEnough = hasNum >= item.amount
	                uiItem:setHasAmount(hasNum)
	                if not isEnough then
						self.isItemEnough = false
	                else
	                	uiItem:setNumberColor(cc.c3b(255,255,0))
	                end
		            -- local sx = (itemRoot:getContentSize().width - len * uiItem:getContentSize().width) / 2
		            -- uiItem:setPosition(cc.p(sx + (i - 1) * uiItem:getContentSize().width,0))
		            uiItem:updateNumberSize()
		            -- UIHandler:addItemTouch(uiItem,item.tid,nil,Enums.TipsType.item,1 / 2,0.8 / 2)
				end
			end
		end
		if daibiItem then
			local hasNum = UD:getGold()
			needCoinText:setString(hasNum .. "/" .. daibiItem.amount)
			isCoinEnough = hasNum >= daibiItem.amount
			if isCoinEnough then
				needCoinText:setColor(self._coinColor)
			else
				needCoinText:setColor(cc.c4b(255,0,0))
			end
		else
			needCoinText:setString("0/0")
		end

		-- 设置居中
		display.setNodesMiddle(PanelGold, nil, needCoinIcon, needCoinText)
	end
end

function MakeView:updateMakePageIcons(data)
	local productItem = data.productItem

	local makeRootPanel = self._makePage:findChild("Panel/Panel_make")
	local threeIconNode = makeRootPanel:getChildByName("Panel_icon_3")
	local fourIconNode = makeRootPanel:getChildByName("Panel_icon_4")

	local makeCostArray = string_split(data.cost,";")

	if #makeCostArray == 3 then
		threeIconNode:setVisible(true)
		fourIconNode:setVisible(false)
		self:setMakeIcons(threeIconNode,productItem,makeCostArray)
	elseif #makeCostArray == 4 then
		threeIconNode:setVisible(false)
		fourIconNode:setVisible(true)
		self:setMakeIcons(fourIconNode,productItem,makeCostArray)
	end
end

function MakeView:updateMakePage(data)
	-- dump(data," updateMakePage ")
	self._curMakeData = data
	local rootAttrNode = self._makePage:findChild("Panel/Panel_tips")
	local makeRootPanel = self._makePage:findChild("Panel/Panel_make")

	self._makeRoot = makeRootPanel:getChildByName("Panel_made")
	self._stopMakeRoot = makeRootPanel:getChildByName("Panel_stop")
	local toLearnRoot = makeRootPanel:getChildByName("Panel_stude")
	local noResourceTips = makeRootPanel:getChildByName("Panel_lv")

	local btnGoText = toLearnRoot:findChild("Button_go/name")
	--local tempList = nil

	local btnGo = toLearnRoot:getChildByName("Button_go")
	btnGo:addClickEventListener(function(sender)
		if data.gotoFeature then
			local itemInfo = data.peifangItem
			local resource = GD:getConvertResource(data.gotoFeature, itemInfo.itemBagType, itemInfo:getId(), itemInfo:getSubMenu())
			app:sendMsg( "HandbookController", "openGotWayView", resource )
		end
	end)

	if UD:isHasFormula(data.id,self._model:getCurSkillId()) then
		self:showMakePanel()
		self:setMakeSelPanel(data)
		toLearnRoot:setVisible(false)
		noResourceTips:setVisible(false)
		self._makeRoot:setVisible(true)
	else
		if data.gotoFeature then
			--tempList = string_split( data.gotoFeature, "|" )
			btnGoText:setString( L("lua_code_text_511") )
			toLearnRoot:setVisible(true)
			noResourceTips:setVisible(false)
		else
			noResourceTips:getChildByName("tips_down"):setString( L("formulaUpgradeToUnlock") )
			toLearnRoot:setVisible(false)
			noResourceTips:setVisible(true)
		end
		self._makeRoot:setVisible(false)
	end


	self._stopMakeRoot:setVisible(false)
	local productItem = data.productItem
	local rootAttrPanel = rootAttrNode:getChildByName("Panel")
	local itemRoot = rootAttrPanel:getChildByName("Panel_top")
	self._dataRoot = rootAttrPanel:getChildByName("Panel_data")
	self._suitRoot = rootAttrPanel:getChildByName("Panel_suit")
	self._jewelRoot = rootAttrPanel:getChildByName("Panel_jewel")
	self._makeExpRoot = rootAttrPanel:getChildByName("Panel_make")
	self._desRoot = rootAttrPanel:getChildByName("Panel_text_1")
	local desText = self._desRoot:getChildByName("Text")
	local lookBtn 		= rootAttrNode:findChild("Panel/btn_look")
	lookBtn:setVisible(false)
	if productItem then
		local isShow , param = productItem:isClassAvatarEnable()
		lookBtn:setVisible(isShow)
		lookBtn:addClickEventListener(function()
			 EM:notify("avatarPreview", param)
		end)
	end

	self._model:setAttrBeginningPosition(cc.p(self._dataRoot:getPosition()))

	local iconNode = itemRoot:getChildByName("icon")
	local itemType = itemRoot:getChildByName("type")
	local itemName = itemRoot:getChildByName("Name")
	local canEquipText = itemRoot:getChildByName("lv_tlt")
	local combat_tlt = itemRoot:getChildByName("combat_tlt")
	local combat_num = itemRoot:getChildByName("combat_num")

	local costPowerText = self._makeExpRoot:getChildByName("data_num_1")
	local getExpText = self._makeExpRoot:getChildByName("data_num_2")

	costPowerText:setString(data.powerCost)
	getExpText:setString(data.getExp)

	self:updateMakePageIcons(data)


	if productItem then
	    local uiItem = IconRender.create(iconNode)
	    uiItem:setData(data.productItem)
	    uiItem:setClickEnable(false)

	    itemName:setString(productItem:getName())
	    local color = Enums.QualityColor[productItem.quality]
	    if color then
	        itemName:setTextColor(color)
	    end
	    if productItem.itemBagType == Enums.ItemBagType.equip then -- 装备？
	    	-- print("##############   是装备     ·")
	    	canEquipText:setVisible(true)
	    	combat_num:setVisible(true)
	    	itemType:setVisible(true)
	    	itemType:setString(productItem:getPosName())
	    	combat_tlt:setString(L("text_12100014"))
	    	combat_num:setString(productItem:getGearScore())
	    	local equipLvStr = (productItem.useLv ~= nil) and string.format(L("tips_3000333"),productItem.useLv) or ""

	    	canEquipText:setString(equipLvStr)
	    	desText:setString( productItem:getDesc() )

        	local attrs = productItem:getStrengthAttr(0)

        	local props = {}
        	for k,v in pairs(attrs) do
        		local attr1,attr2,attr3 = UD:formatAttr(k,v)
        		local attr = {Title = attr1,Txt = attr2}
        		table.insert(props,attr)
        	end

	    	if props and #props > 0 then
				for i = 1,3 do
					local name = "data_" .. i
					local dataNode = self._dataRoot:getChildByName(name)
					if dataNode then
						local prop = props[i]
						if prop then
							dataNode:setVisible(true)
							local attRender = AttrRender.createWithData(prop,dataNode,2)
						else
							dataNode:setVisible(false)
						end
					end
				end
				-- 以下：调整装备属性panel高
				local width = self._dataRoot:getContentSize2()
				local offsetY = ( 3 - #props ) * dataAttrPanelHeight
				self._dataRoot:setContentSize( cc.size( width, dataPanelOriginHeight - offsetY ) )
				-- 以下：调整装备属性posY位置
				self._dataRoot:getChildByName( "line" ):setPositionY( dataLineOriginPos - offsetY )
				self._dataRoot:getChildByName( "data_1" ):setPositionY( dataAttrOriginPos_1 - offsetY )
				self._dataRoot:getChildByName( "data_2" ):setPositionY( dataAttrOriginPos_2 - offsetY )
				self._dataRoot:getChildByName( "data_3" ):setPositionY( dataAttrOriginPos_3 - offsetY )
				ccui.Helper:doLayout(self._dataRoot)
	    	end

	    	local jewelSlots = productItem.jewelSlots
    		for i = 1,4 do
				local jewelSlot = jewelSlots[i]
    			local name = "jewel_" .. i
    			local jewelNode = self._jewelRoot:getChildByName(name)
				jewelNode:setVisible(jewelSlot ~= nil)
				if jewelSlot then
					self:setSlotNode(productItem,jewelSlot,jewelNode)
				end
    		end
	    elseif productItem.itemBagType == Enums.ItemBagType.item then -- 物品？
	    	-- itemType:setString()
	    	-- print("##############   ··是物品。     ·")
	    	itemType:setVisible(false)
	    	canEquipText:setVisible(false)
	    	combat_num:setVisible(false)
	    	combat_tlt:setString(productItem:getTypeName())
	    	desText:setString( productItem:getDesc() )
	    end

	    self:changeShowArrrNodePosition(productItem)
	end

end

function MakeView:changeShowArrrNodePosition(productItem)
	self._suitRoot:setVisible(false)
	local addY = 0
	local nodes = {}
	if productItem.itemBagType == Enums.ItemBagType.equip then
		-- nodes = {self._dataRoot,self._jewelRoot,self._makeExpRoot,self._desRoot}
		table.insert( nodes, self._dataRoot )
		if productItem:canSetJewel() then -- 有宝石孔？
			table.insert( nodes, self._jewelRoot )
		else
			self._jewelRoot:setVisible( false )
		end
		table.insert( nodes, self._makeExpRoot )
		local descStr = self._desRoot:getChildByName("Text"):getString()
		if "" ~= descStr then
			table.insert( nodes, self._desRoot )
		else
			self._desRoot:setVisible( false )
		end
	elseif productItem.itemBagType == Enums.ItemBagType.item then
		self._dataRoot:setVisible(false)
		self._jewelRoot:setVisible(false)
		nodes = {self._makeExpRoot,self._desRoot}
		addY = 20
	end
	local bPosition = self._model:getAttrBeginningPosition()
	local x = bPosition.x
	local tHeight = 0
	for i,node in ipairs(nodes) do
		local y = bPosition.y + addY - tHeight
		node:setVisible(true)
		node:setPosition(cc.p(x,y))
		tHeight = tHeight + node:getContentSize().height
	end
end

function MakeView:updateMakeSelPanel()
	local makeRoot = self._makeRoot
	local root = makeRoot:getChildByName("Panel_supplies")
	local powerRoot = makeRoot:getChildByName("Panel_enter")
	local makeNumText = root:getChildByName("make_num")
	local makeExpText = root:getChildByName("make_exp_num")
	local makePowerCostText = powerRoot:findChild("power/num_gold")
	if not self._oMakePowerTextColor then
		self._oMakePowerTextColor = makePowerCostText:getColor()
	end

	local data = self._model:getMakeData()
	local makeNum = self._model:getMakeNum()

	makeNumText:setString( L("lua_code_text_517") .. makeNum )
	local getExp = data.getExp * makeNum

	local str = table.concat( { L("getformulaexp"), "+", getExp } )
	makeExpText:setString( str )
	local powerCost = tonumber(data.powerCost) * makeNum
	local costStr = UD:getPower() .. "/" .. powerCost
	makePowerCostText:setString(costStr)
	local color
	if self._model:isPowerEnough(powerCost) then
		color = self._oMakePowerTextColor
	else
		color = cc.c3b(255,0,0)
	end
	makePowerCostText:setColor(color)
end


function MakeView:setMinusBtnEnabled()
	local makeRoot = self._makeRoot
	local root = makeRoot:getChildByName("Panel_supplies")
	local btnMinus = root:getChildByName("Button_minus")
	local btnPlus = root:getChildByName("Button_plus")
	local btnMax = root:getChildByName("Button_max")

	local maxNum = self._model:getMaxMakeNum()
	display.setBtnTouchEnable(btnMinus,not (self._model:getMakeNum() <= 1))
	display.setBtnTouchEnable(btnPlus,not (self._model:getMakeNum() >= maxNum))
	display.setBtnTouchEnable(btnMax,not (self._model:getMakeNum() >= maxNum))
end

function MakeView:setMakeSelPanel(data)
	self._model:setMakeData(data)
	local makeRoot = self._makeRoot
	local root = makeRoot:getChildByName("Panel_supplies")
	local powerRoot = makeRoot:getChildByName("Panel_enter")
	local btnMinus = root:getChildByName("Button_minus")
	local btnPlus = root:getChildByName("Button_plus")
	local btnMake = powerRoot:getChildByName("Button_enter")
	local btnMax = root:getChildByName("Button_max")

	self._model:setMakeNum(1)

	self:updateMakeSelPanel()

	self:setMinusBtnEnabled()

	btnMinus:addClickEventListener(function(send)
		local curMakeNum = self._model:getMakeNum()
		local makeNum = ((curMakeNum - 1) <= 0) and curMakeNum or (curMakeNum - 1)
		self._model:setMakeNum(makeNum)
		self:updateMakeSelPanel()
		self:setMinusBtnEnabled()
	end)
	btnPlus:addClickEventListener(function(send)
		local curMakeNum = self._model:getMakeNum()
		local maxNum = self._model:getMaxMakeNum()
		local makeNum = ((curMakeNum + 1) > maxNum) and maxNum or curMakeNum + 1
		self._model:setMakeNum(makeNum)
		self:updateMakeSelPanel()
		self:setMinusBtnEnabled()
	end)

	btnMax:addClickEventListener(function(send)
		-- local curMakeNum = self._model:getMakeNum()
		local makeNum = self._model:getMaxMakeNum()
		self._model:setMakeNum(makeNum)
		self:updateMakeSelPanel()
		self:setMinusBtnEnabled()
	end)

	btnMake:addClickEventListener(function(sender)
		if data.level < data.manufacturingLv then
			display.pushToast(L("manufactureLevelLess"))
			return
		end

		if self._model:isPowerEnough(tonumber(data.powerCost) * self._model:getMakeNum()) then
			--判断背包是否满了
			local bagModel = app:getInst("NewBagModel")
			if bagModel:isBagFull() then
				display.pushToast(L("tips_1990041"))
				return
			end

			if self._model:isMakeItemEnough() then
				self:showStopMakePanel()
				self:hideMakePanel()
				self:startMakeProgress()
			else
				display.pushToast(L("tips_1020014"))
			end
		else
			display.pushToast(L("tips_1020005"))
		end

	end)
end

function MakeView:setMakeIcons(iconRoot,productItem,makeCostArray)
	if not productItem then return end
	local buildIconNode = iconRoot:getChildByName("icon")
	if buildIconNode then
	    local uiItem = IconRender.create(buildIconNode)
	    uiItem:setData(productItem)
	    uiItem:setClickEnable(false)
	end

	self._model:setMakeItemEnough(true)
	for i = 1,4 do
		local name = "icon_" .. i
		local iconNode = iconRoot:getChildByName(name)
		if iconNode then
			local makeCost = makeCostArray[i]
			if makeCost then
				iconNode:setVisible(true)
				local item = UD:parseRewardToBagItem(makeCost,"|")
				if item then
				    local uiItem = IconRender.create(iconNode)
				    uiItem:setData(item)
				    uiItem:setTipEnable(true)
		            uiItem:setNumBgVisible(true)
					local hasNum = UD:getNumByRenderData( item )
	                local isEnough = hasNum >= item.amount
	                uiItem:setHasAmount(hasNum)
	                uiItem:updateNumberSize()
	                -- UIHandler:addItemTouch(iconNode,item.tid,nil,Enums.TipsType.item,0.8 / 2,1.2 / 2)

	                if not isEnough then
	                	self._model:setMakeItemEnough(false)
	                else
	                	uiItem:setNumberColor(cc.c3b(255,255,0))
	                end
	            else
	            	iconNode:setVisible(false)
				end
			else
				iconNode:setVisible(false)
			end
		end
	end
end

function MakeView:setSlotNode(productItem,slot,slotNode)
	local bgNode = slotNode:findChild("Panel/bg")
	local iconNode = slotNode:findChild("Panel/icon")
	bgNode:setVisible(true)
	iconNode:setVisible(false)
	if slot then
		bgNode:loadTexture(slot:getIcon())
	else
		bgNode:setVisible(false)
	end
end

function MakeView:showStopMakePanel()
	if not self._stopMakeRoot then return end
	self._stopMakeRoot:setVisible(true)

	local btnStop = self._stopMakeRoot:getChildByName("Button_stop")
	btnStop:addClickEventListener(function(sender)
		self:stopMakeProgress()
	end)
end

function MakeView:hideStopMakePanel()
	if not self._stopMakeRoot then return end
	self._stopMakeRoot:setVisible(false)
	self._stopMakeRoot:stopAllActions()
end

function MakeView:showMakePanel()
	if not self._makeRoot then return end
	self._makeRoot:setVisible(true)
end

function MakeView:hideMakePanel()
	if not self._makeRoot then return end
	self._makeRoot:setVisible(false)
end

function MakeView:startMakeProgress()
	if not self._stopMakeRoot then return end
	local progressBar = self._stopMakeRoot:findChild("Panel_bar/LoadingBar")
	local makeNumText = self._stopMakeRoot:findChild("Panel_bar/num")

	makeNumText:setString(self._model:getMakeNum())
	progressBar:setPercent(0)
	local intervalTime = 0.05
	local totalTime = 3.0
	local iCount = math.ceil(totalTime / intervalTime)
	local intervalPercent = 101 / iCount
	self._stopMakeRoot:runAction(cc.Repeat:create(cc.Sequence:create(cc.DelayTime:create(intervalTime),cc.CallFunc:create(function()
		local percent = progressBar:getPercent() + intervalPercent
		progressBar:setPercent(percent)
		if percent >= 100 then
			self._stopMakeRoot:stopAllActions()
			self._model:C2S_Composite()
		end
	end)),iCount))
end

function MakeView:stopMakeProgress()
	self:showMakePanel()
	self:hideStopMakePanel()
end

function MakeView:makeSuccess()
	--if self._model:getMakeNum() > 1 then
		--self._model:setMakeNum(self._model:getMakeNum() - 1)
		--self:updateMakeSelPanel()
		--self:startMakeProgress()
	--else
		self._model:setMakeNum(1)
		self:stopMakeProgress()
		self:updateMakeSelPanel()
	--end
	local curFormulaData = self._model:getCurFormulaData()
	if curFormulaData then
		local sub = self._model:getInfoByLevelId(curFormulaData.nodeMenuLevel,curFormulaData.id)
        if sub then
	        self:updateMakePageIcons(sub)
        end
	end
end

function MakeView:makeFaield()
	self:stopMakeProgress()
	self:updateMakeSelPanel()
end

function MakeView:lifeLevelUpSuccess()
	local makeInfo = self._model:getCurMakeInfo()
	if makeInfo then
		local sub = self._model:getInfoByLevelId(makeInfo.nodeMenuLevel,makeInfo.id)
		if sub then
			self:updateMainPage(sub)
			for i,v in ipairs(self._makeInfoItems) do
				if v:getId() == sub.id then
					v:setLevel(sub.level)
				end
			end
		end
	end
end

function MakeView:switchOption(isMake)

	self._toolsNode:setVisible(not isMake)
	self._makeNode:setVisible(isMake)

	self._btnMake:setBright(not isMake)
	self._btnTools:setBright(isMake)
end

function MakeView:updateMakeListLastItemBorder()
	local max = #self._makeList:getItems() - 1
	-- print("############。updateMakeListLastItemBorder max   ",max)
	for i,v in ipairs(self._makeList:getItems()) do
		local index = self._makeList:getIndex(v)
		v.makeItem:updateLastItem(index == max)
	end
end

function MakeView:fillMakeList(params)
	self._makeList:removeAllChildren()
	self:getCurrentNewGetFormulaInfos()

	local flag = true -- params ~= nil 选中特定的道具之后置为false
    local function showSubMenum(sender,subs)
        if not subs then return end
		--dump(subs,"##########  fillMakeList ")
        for i,sub in ipairs(subs) do
            local makeItem = MakeItem.new()
            local itemNode = makeItem:createWithData(nil,sub)
            if sender == nil and sub.id == 101 then
            --默认的职业技能刷新名称
            	makeItem:updateToClassName()
            end
            itemNode.makeItem = makeItem
            if sub.nodeMenuLevel == 1 then
            	table.insert(self._makeInfoItems,makeItem)
            end

            if sender then
                self._makeList:insertCustomItem(itemNode,self._makeList:getIndex(sender) + 1)
            else
                self._makeList:pushBackCustomItem(itemNode)
			end


			--根据当前的newGetFirst newGetSub来设置相应红点
			if self._newGetFirstTypes[sub.id] or self._newGetSubTypes[sub.id] or UD:isFormulaNewGet(sub.id) then
				makeItem:setDotVisible(true)
			else
				makeItem:setDotVisible(false)
			end

            local function openMenu(sender,itemNode,sub)
            	self._curOpSubTemp = sub

            	self:stopMakeProgress()

            	if sub.nodeMenuLevel == 3 then
            		local sub = self._model:getInfoByLevelId(sub.nodeMenuLevel,sub.id)
            		if sub then
	            		self._model:setCurFormulaData(sub)
	            		self:switchMakePage(true)
						--print("########     点击三级菜单。    ")
	            		self:updateMakePage(sub)
						if UD:isFormulaNewGet(sub.id) then
							UD:setFormulaNewGet(sub.id, false)
							itemNode.makeItem:setDotVisible(false)
							self:getCurrentNewGetFormulaInfos()
							--同时要判断上层的红点是否要去掉
							self:refreshMakeItemListRedPoint()
							UD.redPoint:checkStateByKey(Constant.FUNC_TYPE_COMPOUND)
						end
            		end
            	else
            		self:switchMakePage(false)
            		if sub.nodeMenuLevel == 1 then
            			local sub = self._model:getInfoByLevelId(sub.nodeMenuLevel,sub.id)
            			-- print("########     点击一级菜单。    ")
            			if sub then
	            			self._model:setCurMakeInfo(sub)
	            			self:updateMainPage(sub,makeItem:getName())
            			end
            		elseif sub.nodeMenuLevel == 2 then
            			local curInfo = self._model:getCurMakeInfo()
            			if curInfo then
            				local sub = self._model:getInfoByLevelId(curInfo.nodeMenuLevel,curInfo.id)

            				self:updateMainPage(sub)
            			end

            		end
				end
				
				if not itemNode.isOpen then
            		self:removeItemNodesByLevel(sub.nodeMenuLevel)
            		itemNode.isOpen = true
            		makeItem:showOpenArrow(itemNode.isOpen)
            		makeItem:switchOn(itemNode.isOpen)
            		showSubMenum(itemNode,sub.subs)
            		local index = self._makeList:getIndex(itemNode)
        			self._makeList:scrollToPercentVertical(100 * index / #(self._makeList:getChildren()), 0.3, true)
				else
            		itemNode.isOpen = false
            		self:removeItemNodesByLevel(sub.nodeMenuLevel)
				end
				
            	self:updateMakeListLastItemBorder()
            end

            makeItem:setOnClick(function(sender)
            	openMenu(sender,itemNode,sub)
            end)

			if params ~= nil and flag then -- 如果直接跳转到三级菜单，先选中一级，再选二级，再选三级 ~_~
				local lifeId = params.lifeId
				local levelId = params.levelId
				local formulaId = params.formulaId
				if not sender and sub.id == lifeId then --选中一级
					openMenu(sender, itemNode, sub)
				elseif sender then
					if levelId == sub.id then -- 选中二级
						openMenu(sender, itemNode, sub)
					elseif formulaId == sub.id then -- 选中三级
						openMenu(sender, itemNode, sub)
					end
				end
			elseif not sender and i == 1 then
            	openMenu(sender,itemNode,sub)
       		end
        end

		self._makeList:refreshView()
		flag = false
    end
    showSubMenum(nil,self._model:getShowMakeInfos())

end

function MakeView:removeItemNodesByLevel(level)
	if not self._makeList or not level then return end
    for k,v in pairs(self._makeList:getChildren()) do
        if v.level > level then
        	local index = self._makeList:getIndex(v)
        	self._makeList:removeItem(index)
        elseif v.level == level then
        	v.isOpen = false
        	v.makeItem:showOpenArrow(v.isOpen)
        	v.makeItem:switchOn(v.isOpen)
        end
    end
    self._makeList:refreshView()
end

--通过userData上的数据 新获得配方 ，来得到到底是第几个
function MakeView:getCurrentNewGetFormulaInfos()
	self._newGetFirstTypes = {} --存放新获得配方是哪个专业的
	self._newGetSubTypes = {} --存放新获得是哪个次级分类的

	local allFormulas = UD:getFormulaIds()
	for k,v in pairs(allFormulas) do
		if v:isNewGet() then
			local fmc = GD:queryFormulaById(k)
			self._newGetFirstTypes[tonumber(fmc.subkey)] = 1
			self._newGetSubTypes[tonumber(fmc.showType)] = 1
		end
	end
end

function MakeView:refreshMakeItemListRedPoint()
	for k,v in pairs(self._makeList:getChildren()) do
		local id = v.makeItem:getId()
		if self._newGetFirstTypes[id] or self._newGetSubTypes[id] then
			v.makeItem:setDotVisible(true)
		else
			v.makeItem:setDotVisible(false)
		end
	end
end

function MakeView:createToolTypeNode(toolName)
	local itemUI = cc.uiloader:load(Res.ToolTypeNode)
    local itemPanel = itemUI:getChildByName("Panel")
    itemUI:setContentSize(itemPanel:getContentSize())

    local nameNode = itemPanel:getChildByName("name")
    nameNode:setString(toolName)

    return itemUI
end

function MakeView:fillToolsMenuList()
	if self._hasFillTools then return end
	self._hasFillTools = true

	self._toolsMenuList:removeAllChildren()

	local sleImages = {}

	local function setSelectedIndex(index)
		local mainType
		for i,v in ipairs(sleImages) do
			if v.index == index then
				v.selImg:setVisible(true)
				mainType = v.mainType
			else
				v.selImg:setVisible(false)
			end
		end
		self:fillToolsList(mainType)
	end

	local toolTypes = GD:getAllToolTypeConfig()
	local index = 1
	for _,toolType in ipairs(toolTypes) do
        local tools = GD:getAllToolConfigByType(toolType)
        local toolCount = #tools
        local haveNum = UD:getToolAmountByMainType(toolType)
		local toolName = L("ToolMainType_" .. toolType) .. "(".. haveNum .. "/" .. toolCount ..")"
		local itemNode = self:createToolTypeNode(toolName)
		self._toolsMenuList:pushBackCustomItem(itemNode)

		local rootPanel = itemNode:getChildByName("Panel")
		rootPanel:setTag(index)
		local selImg = rootPanel:getChildByName("selected")
		rootPanel:setTouchEnabled(true)
		rootPanel:addClickEventListener(function(sender)
			setSelectedIndex(sender:getTag())
		end)
		table.insert(sleImages,{index = index,selImg = selImg,mainType = toolType})

		index = index + 1
	end

	setSelectedIndex(1)
end

function MakeView:createToolNode(data)
	local itemUI = cc.uiloader:load(Res.ToolNode)
    local itemNode = itemUI:getChildByName("Panel")
    itemUI:setContentSize(itemNode:getContentSize())

    local btnGo = itemNode:getChildByName("Button_go")
    local textOver = itemNode:getChildByName("Text_over")
    local nameNode = itemNode:getChildByName("name")
    local desNode = itemNode:getChildByName("Text")
    local iconNode = itemNode:getChildByName("icon")

    local alreadyHave = false
    for _,v in pairs(UD.tools) do
        if tonumber(v.tid) == tonumber(v1.ID) then
            alreadyHave = true
            break
        end
    end

    textOver:setVisible(alreadyHave)
    btnGo:setVisible(not alreadyHave)

    iconNode:loadTexture(GD:formatIconFilePath(Enums.ItemBagType.tool, data.icon))

    nameNode:setString(L(data.name))
    desNode:setString(L(data.desc))

    return itemUI
end

function MakeView:fillToolsList(mainType)
	if not mainType then return end
	self._tollsList:removeAllChildren()

	local tools = GD:getAllToolResByType(mainType)

	for k,v in pairs(tools) do
		local itemNode = self:createToolNode(v)

		self._tollsList:pushBackCustomItem(itemNode)
	end
end

-- 背包中道具发生变化
function MakeView:updateItem()
	if self._curOpSubTemp then
		if self._curOpSubTemp.nodeMenuLevel == 3 then
			local sub = self._model:getInfoByLevelId( self._curOpSubTemp.nodeMenuLevel, self._curOpSubTemp.id )
			if sub then
				self:updateMakePageIcons( sub )
				self:setMinusBtnEnabled()
			end
		else
			local sub
			if self._curOpSubTemp.nodeMenuLevel == 2 then
				local curInfo = self._model:getCurMakeInfo()
				if curInfo then
					sub = self._model:getInfoByLevelId( curInfo.nodeMenuLevel, curInfo.id )
				end
			elseif self._curOpSubTemp.nodeMenuLevel == 1 then
				sub = self._model:getInfoByLevelId( self._curOpSubTemp.nodeMenuLevel, self._curOpSubTemp.id)
			end
			if sub then
				local costArray
				if sub.cost then
					costArray = string_split(sub.cost,";")
				end
				if costArray then
					local items = {}
					for i,v in ipairs( costArray ) do
						local item = UD:parseRewardToBagItem(v)
						if item and item.itemBagType ~= Enums.ItemBagType.daibi then
							table.insert( items, item )
						end
					end
					local len = #items


					local root = self._mainPage:getChildByName("Panel")
					local Panel_need = root:getChildByName("Panel_need")
					local itemRoot = Panel_need:getChildByName("Panel_item")


					for i,item in ipairs(items) do
						local itemNode = itemRoot:getChildByName( "icon_" .. i )
						if itemNode then

							itemNode:setData(item)
							itemNode:setNumBgVisible(true)

							local hasNum = UD:getNumByRenderData( item )
							local isEnough = hasNum >= item.amount
							itemNode:setHasAmount( hasNum )
							if not isEnough then
								self.isItemEnough = false
							else
								itemNode:setNumberColor(cc.c3b(255,255,0))
							end

							itemNode:updateNumberSize()
						end
					end
				end
			end
		end
	end
end

return MakeView
